#include "users.h"

int user_id_min = 100;

// 生成ID
int generate_id_user() 
{
    // 从内存中获取当前最小ID，生成新ID后更新内存
    int new_id = user_id_min;
    user_id_min++;  // 下次ID自增
    return new_id;
}

// 从文件加载设备数据
node_t *load_users()
{
    node_t *head = create_dlist();
    FILE *fp = fopen(USER_FILE, "r");
    
    if (!fp) {  // 文件不存在，初始化
        fp = fopen(USER_FILE, "w+");
        fprintf(fp, "100"); 
        fclose(fp);
        return head;
    }
    
    // 读取第一行（最小ID）
    fscanf(fp, "%d\n", &user_id_min);
    
    users_t temp = {0};
    // 用%31s限制字符串长度，避免溢出
    // 用%[^\n]但需调整分隔逻辑(空格)
    while (fscanf(fp, "%d %15s %15s\n",&temp.user_id, temp.user_name, temp.user_pw )== 3) 
    {
        insert_tdlist(head, &temp, sizeof(users_t));
    }
    
    fclose(fp);
    return head;
}

// 将用户账号保存到文件
int save_users(node_t *head)
{
    SYSERR(NULL,==,head,"head is NULL",-1); 
    FILE *fp = fopen(USER_FILE, "w");
    SYSERR(NULL,==,fp,"fopen failed",-1);

    // 重新计算设备数量并更新序号
    node_t *temp = head->after;
    fprintf(fp,"%d\n",user_id_min);
    
    while(temp != head)
    {   
        users_t *userp = (users_t *)temp->data;
        fprintf(fp,"%d %s %s\n",userp->user_id, userp->user_name, userp->user_pw);
        temp = temp->after;
    }

    fclose(fp);
    destroy_dlist(&head);
    return 0;
}

int add_user(node_t * head, const users_t * newuser)
{
    SYSERR(NULL,==,head,"head is NULL",-1);
    SYSERR(NULL,==,newuser,"newuser is NULL",-1);
    
    users_t temp_dev = *newuser;  
    //尾部插入
    insert_tdlist(head, &temp_dev, sizeof(users_t));

    return 0;
}

int del_user(node_t *head, cmpfun_t cmpfun, const users_t *user)
{
    SYSERR(NULL,==,head,"head is NULL",-1);
    SYSERR(NULL,==,user,"user is NULL",-2);
    node_t *result;
    int delete_count = 0;  
    
    // 循环删除所有匹配的用户
    while ((result = delete_vdlist(head, user, cmpfun)) != NULL)
    {
        delete_count++; 
    }
    
    // 根据删除数量返回相应状态
    if (!delete_count)
        return -1;  // 没有找到可删除的用户
    else
        return 0;   // 成功删除至少一个用户    
}

// 显示用户
void show_users(node_t *head, showfun_t showfun)
{
    SYSERR(NULL,==,head,"head is NULL",); 
    node_t *temp = head->after;
    printf("ID    Name\tPassword\n");
    while (temp != head) 
    {
        showfun(temp->data);
        temp = temp->after;
    }
}

// 查找用户
node_t *find_user(node_t *head, cmpfun_t cmpfun, const users_t *user)
{
    SYSERR(NULL,==,head,"head is NULL",NULL);
    SYSERR(NULL,==,user,"dev is NULL",NULL);
	node_t *result_list = create_dlist();
	node_t *temp = head->after;

	while( temp != head )
	{
        if (cmpfun(temp->data, user) == 0)  
        {
            users_t *user_data = (users_t *)temp->data;
            insert_tdlist(result_list, user_data, sizeof(users_t));
        }
        temp = temp->after;  
	}
    // 如果结果链表为空，销毁并返回NULL
    if (result_list->after == result_list) 
    {
        destroy_dlist(&result_list);
        return NULL;
    }
    return result_list;
}

//排序账号
int sort_users(node_t *head,cmpfun_t cmpfun)
{
	SYSERR(NULL,==,head,"head is NULL",-1);
	node_t *temp = head;
	selectSort_dlist(temp,cmpfun);	
    return 0;
}

// 显示函数
void showUser_All(const void *data)
{
    const users_t *user = (const users_t *)data;
    // 使用固定宽度指定字段宽度，负-表示左对齐，确保各列对齐
	printf("%d   %s\t%s\n",
                user->user_id,
                user->user_name,
                user->user_pw);
}   
//比较函数
int cmpUser_ID(const void *data1, const void *data2)
{
    const users_t *userp1 = (const users_t *)data1;
	const users_t *userp2 = (const users_t *)data2;
	return userp1->user_id - userp2->user_id;
}
int cmpUser_Name(const void *data1,const void *data2)
{
    const users_t *userp1 = (const users_t *)data1;
	const users_t *userp2 = (const users_t *)data2;
	return strcmp(userp1->user_name,userp2->user_name);
}

//登陆检测
int login_check(node_t *head,users_t *user)
{
    SYSERR(head,==,NULL,"head is null",-1);
    SYSERR(user,==,NULL,"head is null",-1);

    node_t *temp = head->after; 
    node_t *start = temp;      

    do {
        // 跳过空数据节点
        if (temp == NULL || temp->data == NULL) 
        {
            temp = temp->after;
            continue;
        }

        // 转换数据类型并验证
        users_t *users_data = (users_t *)temp->data;
        // 确保用户名和密码指针有效
        if (users_data->user_name == NULL || users_data->user_pw == NULL) 
		{
            temp = temp->after;
            continue;
        }

        // 验证用户名和密码
        if (strcmp(users_data->user_name, user->user_name) == 0 && 
            strcmp(users_data->user_pw, user->user_pw) == 0) 
            return 0;  

        temp = temp->after;
    } while (temp != start && temp != NULL); 

    // 3. 未找到匹配用户
    return -1;
}
